package cn.iocoder.yudao.module.dr.service.collectionimageacquisition;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.dr.controller.admin.collectionimageacquisition.vo.CollectionImageAcquisitionAuditReqVO;
import cn.iocoder.yudao.module.dr.controller.admin.collectionimageacquisition.vo.CollectionImageAcquisitionPageReqVO;
import cn.iocoder.yudao.module.dr.controller.admin.collectionimageacquisition.vo.CollectionImageAcquisitionSaveReqVO;
import cn.iocoder.yudao.module.dr.controller.admin.collectionmanagement.vo.CollectionImageImportExcelVO;
import cn.iocoder.yudao.module.dr.controller.admin.collectionmanagement.vo.CollectionImportRespVO;
import cn.iocoder.yudao.module.dr.dal.dataobject.collectionimageacquisition.CollectionImageAcquisitionDO;
import cn.iocoder.yudao.module.dr.dal.dataobject.collectionlinkaddress.CollectionLinkAddressDO;
import cn.iocoder.yudao.module.dr.dal.dataobject.collectionmanagement.CollectionManagementDO;
import cn.iocoder.yudao.module.dr.dal.mysql.collectionimageacquisition.CollectionImageAcquisitionMapper;
import cn.iocoder.yudao.module.dr.dal.mysql.collectionlinkaddress.CollectionLinkAddressMapper;
import cn.iocoder.yudao.module.dr.service.collectionmanagement.CollectionManagementService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.dr.enums.ErrorCodeConstants.COLLECTION_IMAGE_ACQUISITION_NOT_EXISTS;

/**
 * 藏品二维采集信息 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class CollectionImageAcquisitionServiceImpl implements CollectionImageAcquisitionService {

    @Resource
    private CollectionImageAcquisitionMapper collectionImageAcquisitionMapper;

    @Resource
    CollectionLinkAddressMapper collectionLinkAddressMapper;


    @Override
    public Long createCollectionImageAcquisition(CollectionImageAcquisitionSaveReqVO createReqVO) {
        // 插入
        CollectionImageAcquisitionDO collectionImageAcquisition = BeanUtils.toBean(createReqVO, CollectionImageAcquisitionDO.class);
        collectionImageAcquisitionMapper.insert(collectionImageAcquisition);

        createReqVO.getCollectionLinkAddress().forEach(o -> o.setBizType("2"));
        // 插入子表
        createCollectionLinkAddressList(collectionImageAcquisition.getId(), createReqVO.getCollectionLinkAddress());

        // 返回
        return collectionImageAcquisition.getId();
    }

    @Override
    public void updateCollectionImageAcquisition(CollectionImageAcquisitionSaveReqVO updateReqVO) {
        // 校验存在
        validateCollectionImageAcquisitionExists(updateReqVO.getId());
        // 更新
        CollectionImageAcquisitionDO updateObj = BeanUtils.toBean(updateReqVO, CollectionImageAcquisitionDO.class);

        updateReqVO.getCollectionLinkAddress().forEach(o -> o.setBizType("2"));
        // 更新子表
        updateCollectionLinkAddressList(updateReqVO.getId(),"2", updateReqVO.getCollectionLinkAddress());
        collectionImageAcquisitionMapper.updateById(updateObj);
    }

    @Override
    public void deleteCollectionImageAcquisition(Long id) {
        // 校验存在
        validateCollectionImageAcquisitionExists(id);
        // 删除
        collectionImageAcquisitionMapper.deleteById(id);
    }

    private void validateCollectionImageAcquisitionExists(Long id) {
        if (collectionImageAcquisitionMapper.selectById(id) == null) {
            throw exception(COLLECTION_IMAGE_ACQUISITION_NOT_EXISTS);
        }
    }

    @Override
    public CollectionImageAcquisitionDO getCollectionImageAcquisition(Long id) {
        return collectionImageAcquisitionMapper.selectById(id);
    }

    @Override
    public PageResult<CollectionImageAcquisitionDO> getCollectionImageAcquisitionPage(CollectionImageAcquisitionPageReqVO pageReqVO) {
        return collectionImageAcquisitionMapper.selectPage(pageReqVO);
    }

    @Override
    public CollectionImportRespVO saveImportDataList(CollectionManagementService managementService, List<CollectionImageImportExcelVO> iList, Boolean updateSupport, Integer importType) {
        CollectionImportRespVO respVO = CollectionImportRespVO.builder().createNames(new ArrayList<>())
                .updateNames(new ArrayList<>()).failureNames(new LinkedHashMap<>()).build();
        // 校验数据
        CollectionImageAcquisitionDO collection3dAcquisitionDO;
        for (CollectionImageImportExcelVO d : iList) {
            collection3dAcquisitionDO = new CollectionImageAcquisitionDO();

            CollectionManagementDO collectionManagement = managementService.selectByGeneralAccessionNumber(d.getGeneralAccessionNumber());
            if(Objects.isNull(collectionManagement)){
                respVO.getFailureNames().put(d.getImageFilename(), "藏品总登记号不存在");
                continue;
            }
            CollectionImageAcquisitionDO exist = collectionImageAcquisitionMapper.selectByImageFilename(collectionManagement.getId(),d.getImageFilename());
            if (exist != null) {
                if (updateSupport) {
                    BeanUtils.copyProperties(d, collection3dAcquisitionDO);
                    collection3dAcquisitionDO.setCollectionId(collectionManagement.getId());
                    collection3dAcquisitionDO.setId(exist.getId());
                    collectionImageAcquisitionMapper.updateById(collection3dAcquisitionDO);
                    respVO.getUpdateNames().add(d.getImageFilename());
                } else {
                    respVO.getFailureNames().put(d.getImageFilename(), "失败，影像文件名已存在");
                    //throw exception(GlobalErrorCodeConstants.COLLECTION3D_ACQUISITION_EXISTS);
                }
                continue;
            }

            BeanUtils.copyProperties(d, collection3dAcquisitionDO);
            collection3dAcquisitionDO.setCollectionId(collectionManagement.getId());
            collectionImageAcquisitionMapper.insert(collection3dAcquisitionDO);
            respVO.getCreateNames().add(d.getImageFilename());

        }
        return respVO;
    }

    private void createCollectionLinkAddressList(Long collectionId, List<CollectionLinkAddressDO> list) {
        if(list == null || list.size() == 0) {
            return ;
        }
        list.forEach(o -> o.setCollectionId(collectionId));
        collectionLinkAddressMapper.insertBatch(list);
    }

    private void updateCollectionLinkAddressList(Long collectionId,String bizType, List<CollectionLinkAddressDO> list) {
        deleteCollectionLinkAddressByCollectionId(collectionId,bizType);
        if(list == null || list.size() == 0) {
            return ;
        }
        list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createCollectionLinkAddressList(collectionId, list);
    }
    private void deleteCollectionLinkAddressByCollectionId(Long collectionId,String bizType) {
        collectionLinkAddressMapper.deleteByCollectionIdAndBizType(collectionId,bizType);
    }



    @Override
    public void auditCollectionImageAcquisition(CollectionImageAcquisitionAuditReqVO updateReqVO) {
        LambdaUpdateWrapper<CollectionImageAcquisitionDO> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(CollectionImageAcquisitionDO::getId,updateReqVO.getId())
                .set(CollectionImageAcquisitionDO::getCataloger,updateReqVO.getCataloger())
                .set(CollectionImageAcquisitionDO::getSourceStatus,updateReqVO.getSourceStatus())
                .set(CollectionImageAcquisitionDO::getCatalogDate,updateReqVO.getCatalogDate())
                .set(CollectionImageAcquisitionDO::getAuditOpinion,updateReqVO.getAuditOpinion())
                .set(CollectionImageAcquisitionDO::getSubmitAuditDate,updateReqVO.getSubmitAuditDate());
        collectionImageAcquisitionMapper.update(null,updateWrapper);

    }
}